﻿// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "pch.h"
#include "stringUtils.h"

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

/* 下面是自定义代码 */
// 宽字符转多字节字符串
char* Wide2Mult(wchar_t* ws) {
	// 宽字符 ws 转换多字节字符串后的长度
	int bufSize = WideCharToMultiByte(CP_ACP, NULL, ws, -1, NULL, 0, NULL, FALSE);
	char *sp = new char[bufSize];
	WideCharToMultiByte(CP_ACP, NULL, ws, -1, sp, bufSize, NULL, FALSE);
	return sp;
}

char* ConstWide2Mult(const wchar_t* ws) {
	// 宽字符 ws 转换多字节字符串后的长度
	int bufSize = WideCharToMultiByte(CP_ACP, NULL, ws, -1, NULL, 0, NULL, FALSE);
	char *sp = new char[bufSize];
	WideCharToMultiByte(CP_ACP, NULL, ws, -1, sp, bufSize, NULL, FALSE);
	return sp;
}

// 多字节字符串转宽字符
wchar_t* Mult2Wide(char* ms) {
	// 多字节字符串转换宽字符后的长度
	int bufSize = MultiByteToWideChar(CP_ACP, 0, ms, -1, NULL, 0);
	wchar_t* wp = new wchar_t[bufSize];
	MultiByteToWideChar(CP_ACP, 0, ms, -1, wp, bufSize);
	return wp;
}

wchar_t* ConstMult2Wide(const char* ms) {
	// 多字节字符串转换宽字符后的长度
	int bufSize = MultiByteToWideChar(CP_ACP, 0, ms, -1, NULL, 0);
	wchar_t* wp = new wchar_t[bufSize];
	MultiByteToWideChar(CP_ACP, 0, ms, -1, wp, bufSize);
	return wp;
}

/*
调用案例

在调用者的头文件中贴入下面的代码
#pragma comment(lib, "../debug/stringUtils.lib")
extern "C" {
	_declspec(dllimport) char* Wide2Mult(wchar_t* ws);
	_declspec(dllimport) char* ConstWide2Mult(const wchar_t* ws);
	_declspec(dllimport) wchar_t* Mult2Wide(char* ms);
	_declspec(dllimport) wchar_t* ConstMult2Wide(const char* ms);
}


void TestMult2WideWindowsAPI() {
	// 将宽字符转换为做字节字符串
	const wchar_t* wideStr = L"测试宽字符串abc123中国";
	char* convertedMultStr = Wide2Mult(wideStr);
	printf("从宽字符转换来的多字节字符串：%s\n", convertedMultStr);

	// 将多字节字符串转换为宽字符
	const char* oriMultStr = "我原本就是多字节abc123字符串";
	wchar_t* convertedWideStr = Mult2Wide(oriMultStr);
	setlocale(LC_ALL, "chs");// 打印宽字符之前要设定好字符集
	wprintf_s(L"从多字节转换来的宽字符：%s\n", convertedWideStr);
}
 */